# coding:utf-8
"""
Created on 2017/12/26

@author: lby
"""
from pymongo.collection import Collection
from cerberus import Validator


class PyCollection(Collection):
    def __init__(self, database, name, create=False, codec_options=None,
                 read_preference=None, write_concern=None, read_concern=None,
                 session=None, scheme=None, **kwargs):
        self.scheme = scheme
        self.validator = Validator()

        super(PyCollection, self).__init__(database, name, create=create, codec_options=codec_options,
                                           read_preference=read_preference, write_concern=write_concern,
                                           read_concern=read_concern,
                                           session=session, **kwargs)

    def insert_one(self, document, bypass_document_validation=False,
                   session=None):
        if self.scheme:
            if self.validator.validate(document, self.scheme):
                return super(PyCollection, self).insert_one(document, bypass_document_validation=False, session=None)
            else:
                return self.validator.errors
        else:
            return super(PyCollection, self).insert_one(document, bypass_document_validation=False, session=None)


class MDB:
    def __init__(self, database, prefix=''):
        self._database = database
        self._prefix = prefix

    def __getattr__(self, name):
        """Get a collection of this database by name.

        Raises InvalidName if an invalid collection name is used.

        :Parameters:
          - `name`: the name of the collection to get
        """
        if name.startswith('_'):
            raise AttributeError(
                "Database has no attribute %r. To access the %s"
                " collection, use database[%r]." % (name, name, name))
        return self.__getitem__(name)

    def __getitem__(self, name):
        """Get a collection of this database by name.

        Raises InvalidName if an invalid collection name is used.

        :Parameters:
          - `name`: the name of the collection to get
        """
        return PyCollection(self._database, self._prefix + name)
